package com.sunshine.ssm.mq.receiver;

import com.sunshine.ssm.mq.InterfaceCallLog;
import com.sunshine.ssm.mq.InterfaceTypeEnum;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;

import java.util.Date;

/**
 * 消息队列监听
 * @Author: WeiHong
 * @Date: 2017/3/29 16:55
 */
public abstract class AbstractListener implements MessageListener {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 具体的业务处理逻辑
     *
     * @param msgBody json消息体
     */
    protected abstract void handleMessage(InterfaceCallLog callLog, String msgBody) throws Exception;

    /**
     * 设置接口类型
     *
     * @return 接口类型
     */
    protected abstract InterfaceTypeEnum setInterfaceTypeEnum();

    @Override
    public void onMessage(Message message) {
        logger.info("MQ监听队列:监听到:[{}]消息.", setInterfaceTypeEnum().getDesc());
        InterfaceCallLog callLog = new InterfaceCallLog();
        callLog.setInterfaceTypeEnum(setInterfaceTypeEnum());
        callLog.setCallTime(new Date());
        callLog.setSuccess(true);
        String msgBody;
        try {
            msgBody = new String(message.getBody(), "UTF-8");
            callLog.setReturnData(msgBody);
            handleMessage(callLog, msgBody);
        } catch (Exception e) {
            logger.error("MQ消费队列==>{},处理异常", setInterfaceTypeEnum().getDesc(), e);
            callLog.setSuccess(false);
            callLog.setExceptionTrace(ExceptionUtils.getStackTrace(e));
        } /*finally {
            try {
                interfaceCallLogService.createOrUpdateInterfaceCallLog(callLog);
            } catch (Exception e) {
                logger.error("保存MQ消费日志报错", e);
            }
        }*/
    }
}
